<template>
  <j-modal
    :confirmLoading="confirmLoading"
    :title="title"
    :visible="visible"
    :width="800"
    switchFullscreen
    cancelText="关闭"
    @cancel="handleCancel"
    @ok="handleOk">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button v-if="!disableSubmit" type="primary" @click="handleOk">确认</a-button>
    </template>
    <a-divider style="font-weight: 600;margin-top: 0px;" orientation="left">基本信息</a-divider>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-col :md="12" :sm="24">
          <a-form-item label="选择人员" v-if="!itemShow" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-search v-decorator="['fullName',validatorRules.fullName]" :disabled="disableSubmit"
                            enter-button placeholder="请选择人员" readOnly @search="productSearch2('superiorUser')"/>
            <a-input readOnly type="hidden" v-decorator="[ 'parentUserName', {}]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="人员职位">
            <a-input v-decorator="['visitPosName']" :disabled="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="所属组织">
            <a-input v-decorator="['visitOrgName']" :disabled="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol" :wrapperCol="wrapperCol"
            label="线路组名称">
            <a-input v-decorator="['groupName', validatorRules.groupName]" :disabled="disableSubmit"
                     placeholder="请输入"/>
          </a-form-item>
        </a-col>
        <a-divider style="font-weight: 600;margin-top: 0px;" orientation="left">线路组明细</a-divider>
        <a-tabs ref="tabs" defaultActiveKey="1" @change="cutType">
          <a-tab-pane key="1" tab="经销商"></a-tab-pane>
          <a-tab-pane key="2" tab="门店"></a-tab-pane>
        </a-tabs>
        <div>
          <a-button style="margin: 10px 30px 0px 30px;" @click="handleAdd" type="primary">新增</a-button>
          <!--        <a-button style="margin: 10px 30px 0px 0px;"type="primary"   @click="">删除</a-button>-->
          <!--            <a-button style='margin: 10px 30px 0px 0px;' @click='' type='primary'>导入</a-button>-->
        </div>

        <div style="padding: 10px 20px">
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="showType?columns2: columns"
            :dataSource="showType?dataSource2:dataSource"
            :pagination="showType?ipagination2:ipagination"
            :loading="loading"
            :scroll="{x:400,y:240 }"
            :rowSelection="{selectedRowKeys:showType? selectedRowKeys2:selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">
            <span slot="action" slot-scope="text, record">
               <a :disabled="disableSubmit" style="color: red;" @click="handleDelete(record)">删除</a>
            </span>
          </a-table>
        </div>
        <my-shuttle-modal
          ref="orgShuttleModal"
          title="选择经销商"
          :searchConfig="orgSearchConfig"
          :columns="orgColumns"
          :positionCode="objs.positionCode"
          :columns2="orgColumns2"
          leftUrl="/customerExtendController/findPageListByPositionCode"
          keyVal="custCode"
          @chooseOk="chooseOk"
        ></my-shuttle-modal>
        <my-shuttle-modal
          ref="cusShuttleModal"
          title="选择门店"
          keyVal="terminalCode"
          :positionCode="objs.positionCode"
          :searchConfig="cusSearchConfig"
          :columns="cusColumns"
          :columns2="cusColumns2"
          leftUrl="/cnTerminalExtendController/findPageListByPositionCode"
          @chooseOk="chooseOk2"
        ></my-shuttle-modal>
      </a-form>
    </a-spin>
    <proChose ref="prochoose2" v-bind="modalProps" :name="title2" @okbro="okbropro2"></proChose>
  </j-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import myShuttleModal from '../../../../components/cn-components/CnShuttleModal'
import proChose from '@comp/cn-components/ProChose'
import JSelectUserPosition from '../../../../components/cn-select-popup/JSelectUserPosition'

export default {
  name: 'SfaVisitGroupModal',
  components: {
    JSelectUserPosition,
    proChose,
    myShuttleModal
  },
  data() {
    return {
      title: '操作',
      title2:"用户",
      visible: false,
      showType: 0,
      positionCode: '',
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      objs: [],
      productSearch2(status) {
        this.$refs.prochoose2.rowKey = 'id'
        let formconfig = [{
          key: 'userName',
          label: '用户账户'
        },
          {
            key: 'realName',
            label: '用户名称'
          }
        ]
        let tableconfig = {
          columns: [{
            title: '用户账户',
            align: 'left',
            dataIndex: 'userName',
            width: 120,
            ellipsis: true
          },
            {
              title: '用户名称',
              align: 'left',
              dataIndex: 'realName',
              width: 120,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/cnUserController/getPageListUser',
          name: '人员',
          multiple: false,
          columW: 10
        }

        // this.name = '用户'
        let dataSource = []
        if (this.form.getFieldValue('superiorUser')) {
          dataSource = [{
            userName: this.form.getFieldValue('superiorUser'),
            realName: this.form.getFieldValue('realsname')
          }]
        }
        this.$refs.prochoose2.isorter = { permflag: 'visit_detail_save_impl' }
        this.$refs.prochoose2.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
      },
      validatorRules: {
        fullName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        classifyName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        classifytotName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        groupName: {
          rules: [{
            required: true,
            message: ''
          }]
        }
      },
      dataSource: [],
      dataSource2: [],
      clientVos: [],
      fileList: [],
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      selectedRowKeys2: [],
      /* table选中records*/
      selectionRows2: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        }
      },
      ipagination2: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        }
      },
      columns: [
        {
          title: '经销商编号',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      columns2: [
        {
          title: '门店编号',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      //组织查询
      orgSearchConfig: [
        {
          type: 'input',
          placeholder: '经销商编号',
          name: 'custCode'
        },
        {
          type: 'input',
          placeholder: '经销商名称',
          name: 'custName'
        }
      ],
      orgColumns: [

        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        }
      ],
      orgColumns2: [
        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      //终端查询
      cusSearchConfig: [
        {
          type: 'input',
          placeholder: '门店编码',
          name: 'terminalCode'
        },
        {
          type: 'input',
          placeholder: '门店名称',
          name: 'terminalName'
        }
      ],
      cusColumns: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        }
      ],
      cusColumns2: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      confirmLoading: false,
      form: this.$form.createForm(this),
      url: {
        add: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitGroupController/saveOrUpdate'
      }
    }
  },
  created() {
  },
  methods: {
    add() {
      this.visible = true
      this.form.resetFields()
    },
    cutType(key) {
      if (key == '1') {
        this.showType = false
      } else {
        this.showType = true
      }
    },
    handleDelete(e) {
      if (this.showType) {
        let key = this.dataSource2.map(item => {
          return item.id
        })
        this.dataSource2.splice(key.indexOf(e.id), 1)
      } else {
        let key = this.dataSource.map(item => {
          return item.id
        })
        this.dataSource.splice(key.indexOf(e.id), 1)
      }
    },
    chooseOk(e) {
      this.dataSource = []
      let key = this.dataSource.map(item => {
        return item.custCode
      })
      let that = this
      e.forEach(item => {
        if (key.indexOf(item.custCode) == -1) {
          item.code = item.custCode
          item.name = item.custName
          this.dataSource.push(item)
        }
      })

    },
    chooseOk2(e) {
      this.dataSource2 = []
      let key = this.dataSource2.map(item => {
        return item.terminalCode
      })
      e.forEach(item => {
        if (key.indexOf(item.terminalCode) == -1) {
          item.code = item.terminalCode
          item.name = item.terminalName
          this.dataSource2.push(item)
        }
      })

    },
    onSelectChange(selectedRowKeys, selectionRows) {
      if (this.showType) {
        this.selectedRowKeys2 = selectedRowKeys
        this.selectionRows2 = selectionRows
      } else {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      }
    },
    handleAdd() {
      if (this.showType) {
        this.dataSource2.forEach(item => {
          this.$refs.cusShuttleModal.dataSource2.push({
            terminalName: item.terminalName,
            terminalCode: item.terminalCode
          })
          this.$refs.cusShuttleModal.selectionRows.push({
            terminalName: item.terminalName,
            terminalCode: item.terminalCode
          })
          this.$refs.cusShuttleModal.selectedRowKeys.push(item.terminalCode)
        })
        this.$refs.cusShuttleModal.visible = true
        this.$refs.cusShuttleModal.loadData()
      } else {
        this.dataSource.forEach(item => {
          this.$refs.orgShuttleModal.dataSource2.push({ custName: item.custName, custCode: item.custCode })
          this.$refs.orgShuttleModal.selectionRows.push({ custName: item.custName, custCode: item.custCode })
          this.$refs.orgShuttleModal.selectedRowKeys.push(item.custCode)
        })
        this.$refs.orgShuttleModal.visible = true
        this.$refs.orgShuttleModal.loadData()
      }
    },
    edit(record) {
      console.log(record)
      this.form.resetFields()
      this.model = Object.assign({}, record)
      console.log(this.model)
      for (let i = 0; i < this.model.clientVos.length; i++) {
        if (this.model.clientVos[i].clientType == 1) {
          this.model.clientVos[i].terminalCode = this.model.clientVos[i].clientCode
          this.model.clientVos[i].terminalName = this.model.clientVos[i].clientName
          this.dataSource2.push(this.model.clientVos[i])
        } else {
          this.model.clientVos[i].custCode = this.model.clientVos[i].clientCode
          this.model.clientVos[i].custName = this.model.clientVos[i].clientName
          this.dataSource.push(this.model.clientVos[i])
        }
      }
      this.objs.positionCode = this.model.visitPosCode
      console.log(this.model.clientVos, this.dataSource, this.dataSource2)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'createName', 'createDate', 'createDateTime', 'updateDate', 'updateDateTime', 'updateName', 'positionCode', 'visitPosName', 'custCode', 'custName', 'status', 'deleteStatus', 'remarks', 'saasid', 'groupCode', 'groupName', 'visitPosCode', 'visitPosName', 'username', 'fullName', 'visitOrgCode', 'visitOrgName', 'untitled1', 'untitled'))
        //时间格式化
      })
    },
    okbropro2(val, status, status2) {
      let objs = JSON.parse(JSON.stringify(val[0]))
      this.objs = objs
      this.form.setFieldsValue({
        parentUserName: objs.userName,
        fullName: objs.realName,
        visitPosName: objs.positionName,
        visitOrgName: objs.departName,
        departName: objs.departName,
        departCode: objs.departCode
      })
    },

    // close () {
    //   this.$emit('close');
    //   this.visible = false;
    // },
    handleOk() {
      const that = this
      // 触发表单验证
      let dataSource = this.dataSource.map(type => Object.assign({
        clientCode: type.custCode,
        clientName: type.custName,
        lng: type.longitude,
        lat: type.latitude,
        clientAddress: type.address,
        clientType: 2
      }))
      let dataSource2 = this.dataSource2.map(type => Object.assign({
        clientCode: type.terminalCode,
        clientName: type.terminalName,
        clientAddress: type.address,
        lng: type.longitude,
        lat: type.latitude,
        clientType: 1
      }))
      this.clientVos = dataSource2.concat(dataSource)

      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          httpurl += this.url.add
          method = 'post'
          let formData = Object.assign(this.model, values)
          formData.userName = this.objs.userName
          formData.clientVos = this.clientVos
          formData.visitPosCode = this.objs.positionCode
          formData.positionCode = this.objs.positionCode
          formData.visitPosName = this.objs.positionName
          formData.orgCode = this.objs.departCode
          console.log(formData)
          //时间格式化
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      if (this.ipagination.current !== pagination.current) {
        this.selectionRows = []
        this.selectedRowKeys = []
      }
      this.ipagination = pagination
      // this.loadData()
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
      this.fileList = []
      this.confirmLoading = false
      this.dataSource = []
      this.dataSource2 = []
      this.model = {}
      this.objs = []
    },
    // handleCancel () {
    //   this.close()
    // },
    close() {
      this.handleCancel()
    }

  }
}
</script>

<style lang="less" scoped>

</style>